package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    /**
     * 处理添加购物车的请求
     * @param shoppingCart
     * @param session
     * @return
     */
    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){

        //1.接收请求数据封装到ShoppingCart对象中
        //2.获取登录用户的id封装到ShoppingCart对象中
        Long  id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);

        //3.调用业务进行添加购物车操作
        ShoppingCart shoppingCart1 = shoppingCartService.addCart(shoppingCart);

        //4.设置返回数据,将购物车对象返回
        return R.success(shoppingCart1);
    }

    @RequestMapping ("/sub")
    public R<ShoppingCart> deleteCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){

        //1.接收请求数据封装到ShoppingCart对象中
        //2.获取登录用户的id封装到ShoppingCart对象中
        Long  id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);

        //3.调用业务进行添加购物车操作
        ShoppingCart shoppingCart1 = shoppingCartService.subCart(shoppingCart) ;

        //4.设置返回数据,将购物车对象返回
        return R.success(shoppingCart1);
    }





    /**
     * 查询指定用户的的购物车集合数据
     * @param
     * @param session
     * @return
     */
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAllByUserId(HttpSession session){

        //1.获取登录用户的id
        Long id = (Long) session.getAttribute("user");

        //2.调用业务获取用户的购物车集合数据
        List<ShoppingCart> allByUserId = shoppingCartService.findAllByUserId(id);

        //3.返回购物车集合数据
        return R.success(allByUserId);

    }


    /**
     * 清空购物车的请求
     * @param session
     * @return
     */
    @RequestMapping("/clean")
    public R<String> deleteByUserId(HttpSession session){
        //1.获取用户的id
        Long  id = (Long) session.getAttribute("user");

        //2.调用业务清空购物车
        shoppingCartService.clean(id);

        //返回数据
        return R.success("清空购物车成功");

    }
}
